
from rest_framework.decorators import  action
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from users.models import User,Clazz
from .serializers import UserSerializer, ClazzSerializer, ClazzAndUser
from rest_framework.pagination import PageNumberPagination


class UserView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class =UserSerializer
    pagination_class =PageNumberPagination
    pagination_class.page_size_query_param="rows"


class ClazzView(ModelViewSet):
    queryset = Clazz.objects.exclude(delete=True).order_by('-id')
    serializer_class=ClazzSerializer
    pagination_class =PageNumberPagination
    pagination_class.page_size_query_param = "rows"
    pagination_class.page_size = 10

    def create(self, request, *args, **kwargs):
        clazz_name=request.data.get("name")
        clz=self.get_queryset().filter(name=clazz_name).first()
        if clz is not None:
            return Response({"manage":"班级以存在"},status=400)
        return super().create(request, *args, **kwargs)
    def update(self, request,pk, *args, **kwargs):
        clazz_name=request.data.get("name")
        clz=self.get_queryset().filter(name=clazz_name).first()
        if clz and clz.pk != int(pk):
            return Response({"message":"班级名已存在"},status=400)
        return super().update(request,pk=pk, *args, **kwargs)

    @action(detail=False, methods=['DELETE'], url_path='batch-remove', url_name='batch-remove')
    def batchRemove(self, request, *args, **kwargs):
        print(request.data)
        return Response(status=204)

class NoAuthView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [AllowAny]
    def create(self, request, *args, **kwargs):
        data=request.data
        print(data)
        if ('username' not in data) or ('password' not in data) or ('is_staff' not in data) or('name' not in data):
            return Response({"status":False,"message":"缺少必传参数",},status=400)
        # if data['is_staff']==0:
        #     if "clazz_id" not in data:
        #         return Response({"status": False, "message": "班级不能为空", }, status=400)
        #     if "email" not in data:
        #         return Response({"status": False, "message": "邮件不能为空", }, status=400)

        if User.objects.filter(username=data['username']).exists():
            return Response({"status": False, "message": "用户名以存在", }, status=400)
        if data['is_staff'] == "1":
            user = User.objects.create_user(username=data['username'], password=data['password'],
                                            is_staff=True,is_active=True,name=data['name'])
            user.save()
            return Response({"status": True, "message": "注册成功", }, status=201)
        user = User.objects.create_user(username=data['username'], password=data['password'], is_staff=False,
                                        is_active=False,email=data['username'],name=data['name'],clazz_id=int(data['clazz']))
        user.save()
        # timestamp=md5(f'u={user.pk}&s=zst'.encode("utf-8")).hexdigest()
        # url = f'{request.scheme}://{request.get_host()}/active?u={user.pk}&e=utf8&sign={timestamp}'
        # now=datetime.now()
        # body = f"""
        #         <div style="width: 500px; height: 300px; background-color: #2D93CA;border-radius: 10px; margin: 0 auto; padding: 10px 20px">
        #         <p>亲爱的用户{user.username}您好！</p>
        #         <p>时间：{now.strftime('%Y-%m-%d %H:%M:%S')}这是您的激活网址请点击激活账号 注意30分钟内有效！</p>
        #         <p style="word-break: break-all">
        #             <a href="{url}">{url}</a>
        #         </p>
        #         <p>毛宗祺邮箱官方</p>
        #     </div>
        #     """
        # message = EmailMessage(subject="[qiku]-账号激活", body=body, to=(user.email,))
        # message.content_subtype = "html"
        # message.send()
        return Response({"status": True, "message": "注册成功,请尽快激活", }, status=201)
class ShowClass(ModelViewSet):
    queryset = User.objects.all()
    serializer_class =UserSerializer
    permission_classes = [AllowAny]

    @action(methods=['get'], detail=False,url_path='show-class')
    def show_class(self,request,*args,**kwargs):
        queryset=Clazz.objects.filter(status=True,delete=False)
        serializer = ClazzSerializer(queryset, many=True)
        return Response(data=serializer.data)

    @action(methods=['POST'], detail=False, url_path='register',url_name='register')
    def register(self,request,*args,**kwargs):
        data=request.data
        user=self.get_queryset().filter(username=data['username']).first()
        if user is not None:
            return Response(data={"status":False,'message': '用户名已被注册'}, status=400)
        serializer = self.get_serializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(data={"status":True,'message': '注册成功'}, status=201)
        return Response(data=serializer.errors, status=400)







